package com.example.mystore.servlets.service;

import com.example.mystore.dao.CustomersDao;
import com.example.mystore.entity.Customer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

public class InsertCustomerServlet extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse resp) {
        try {
            req.setCharacterEncoding("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String toURL = "/register.jsp";
        String customerName =req.getParameter("userName");
        String customerEmail =req.getParameter("userEmail");
        String customerPassword =req.getParameter("password");
        String customerAddress =req.getParameter("address");
        String customerPAC =req.getParameter("provincesAndCities");
        String customerPhone =req.getParameter("phone");
        String customerFax =req.getParameter("fax");
        Customer customer = new Customer
                (customerName,customerEmail,customerPassword,customerAddress,customerPAC,customerPhone,customerFax);
//        检验邮箱是否已经注册过
        if (!CustomersDao.checkEmail(customerEmail)) {
//            向数据库写入注册信息
            if (CustomersDao.insertCustomers(customer)) {
//                清除注册错误提醒信息
                req.getSession().removeAttribute("regErr");
                toURL = "/login.jsp";
            }else { req.getSession().setAttribute("regErr","注册失败");}
        }else { req.getSession().setAttribute("regErr","你的邮箱已经注册过是否<a href=\"login.jsp\">返回登录</a>");}
        try {
//            重定向
            resp.sendRedirect(req.getContextPath()+toURL);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
